<template>
  <div class="menu-item-container">
    <div v-if="localType == 'edit' || localType == 'add'">
      <div class="item-title">详情</div>
      <div v-if="localMenu != {}">
        <div class="input-suffix">
          <span>名称：</span>
          <el-input class="input-content" v-model="localMenu.name"> </el-input>
        </div>
        <div class="input-suffix">
          <span>路径：</span>
          <el-input class="input-content" v-model="localMenu.path"> </el-input>
        </div>
        <div class="operate-container">
          <el-button @click="close()">关闭</el-button>
          <el-button
            v-if="type == 'edit' || type == 'add'"
            type="success"
            @click="save()"
            >保存</el-button
          >
        </div>
      </div>
    </div>
    <div v-else>
      <div>
        <li class="el-icon-caret-left"></li>
        请选择菜单
      </div>
    </div>
  </div>
</template>

<script>
import { Button, Input, Message } from "element-ui";
import { UpdateMenu, AddMenu } from "../api/Menu";
export default {
  props: {
    initMenuTreeFn: {
      type: Function,
      required: true,
    },
    menu: {
      type: Object,
    },
    type: {
      type: String,
    },
  },
  data() {
    return {
      localMenu: {}, // 对于数组类型的prop，创建副本
      localType: "",
    };
  },
  components: {
    [Button.name]: Button,
    [Input.name]: Input,
    [Message.name]: Message,
  },
  watch: {
    // 监听yourProp的变化
    menu(newVal, oldVal) {
      // 每当yourProp发生变化时，这个函数就会被调用
      console.log(newVal, oldVal);
      this.localMenu = newVal;
      this.localType = this.type;
    },
  },
  methods: {
    save() {
      var _this = this;
      this.localType = this.type;
      if (this.localType == "edit") {
        UpdateMenu(this.localMenu).then(() => {
          _this.initMenuTreeFn();
          _this.localType = "";
        });
      } else if (this.localType == "add") {
        this.localMenu.id = getRandomIntInclusive(100, 200);
        AddMenu(this.localMenu).then(() => {
          _this.initMenuTreeFn();
          _this.localType = "";
        });
      }
    },
    close() {
      this.localType = "";
    },
  },
  created: function () {
    // `this` 指向 vm 实例
    //console.log("type:", this.type);
  },
};

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>

<style>
.input-content {
  width: 50rem !important;
  margin-top: 20px;
}
.operate-container {
  text-align: center;
  margin-top: 100px;
}
.menu-item-container {
  padding: 20px;
}
.input-suffix > span {
  width: 5rem;
  display: inline-block;
}
.item-title {
  margin-top: 10px;
  margin-bottom: 10px;
  font-weight: bold;
}
</style>
